﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ReplaceFileVersion
{
    public partial class ReplaceFileVersionForm : Form
    {
        public ReplaceFileVersionForm()
        {
            InitializeComponent();
            txtReplacement.Text = DateTime.Now.ToString("yyyyMMddHHmmss");
            folderBrowserDialog1.SelectedPath = txtDir.Text = ReplaceFileVersion.GetDirHistory().FirstOrDefault();
#if DEBUG1
            CheckUpdateForm checkUpdateForm = new CheckUpdateForm();
            checkUpdateForm.ShowDialog(); 
#endif
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtDir.Text.Length == 0 || !Directory.Exists(txtDir.Text))
            {
                MessageBox.Show("目录不存在！", "提示");
                return;
            }
            ReplaceFileVersion.AppendDirHistory(txtDir.Text);
            var fileV = new ReplaceFileVersion(txtDir.Text, txtSearchExt.Text)
            {
                ReplaceMent = ckbAutoRepVal.Checked ? DateTime.Now.ToString("yyyyMMddHHmmss") : txtReplacement.Text
            };
            var list = fileV.Replace();
            var path = fileV.WriteLog(list);
            MessageBox.Show("执行完成！", "提示");
            if (ckbOpenLog.Checked)
            {
                Process.Start(path);
            }
        }

        private void btnSelectDir_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtDir.Text = folderBrowserDialog1.SelectedPath;
                ReplaceFileVersion.AppendDirHistory(folderBrowserDialog1.SelectedPath);
            }
        }

        private void ckbAutoRepVal_CheckedChanged(object sender, EventArgs e)
        {
            txtReplacement.ReadOnly = ckbAutoRepVal.Checked;
            if (ckbAutoRepVal.Checked)
            {
                txtReplacement.Text = "";
            }
        }

        private DirHistoryForm historyForm;
        private void linkLabelHistory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (historyForm != null)
            {
                historyForm.Close();
            }
            historyForm = new DirHistoryForm();
            historyForm.SelectItemEventHandler += (dir) =>
            {
                historyForm.Close();
                txtDir.Text = dir;
                //  MessageBox.Show(dir);
            };
            historyForm.Location = Control.MousePosition;
            //   historyForm.Location=e.Link.Start;
            historyForm.Show();
        }
    }
}
